package cn.qianxun.meta.role.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.qianxun.meta.common.core.dto.RowsData;
import cn.qianxun.meta.common.core.utils.BeanCopyUtils;
import cn.qianxun.meta.common.core.web.dto.SelectLongDTO;
import cn.qianxun.meta.common.core.web.dto.SelectVO;
import cn.qianxun.meta.common.core.web.vo.RemoveLongDTO;
import cn.qianxun.meta.common.log.annotation.Log;
import cn.qianxun.meta.common.log.enums.BusinessType;
import cn.qianxun.meta.role.dto.SysRoleAddDTO;
import cn.qianxun.meta.role.dto.SysRoleQueryDTO;
import cn.qianxun.meta.role.dto.SysRoleStatusDTO;
import cn.qianxun.meta.role.dto.SysUserRoleDTO;
import cn.qianxun.meta.role.entity.SysRole;
import cn.qianxun.meta.role.vo.SysRoleVO;
import cn.qianxun.meta.user.dto.UserDeptRoleSelectDTO;
import cn.qianxun.meta.common.core.domain.Result;
import cn.qianxun.meta.common.excel.utils.ExcelUtil;
import cn.qianxun.meta.dept.entity.SysDept;
import cn.qianxun.meta.dept.service.ISysDeptService;
import cn.qianxun.meta.role.service.ISysRoleService;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 角色信息表 前端控制器
 * </p>
 *
 * @author fuzhilin
 * @since 2023-08-28 09:28:37
 */
@Tag(name = "角色管理")
@Validated
@RestController
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RequestMapping("/web/v1/sysRole")
public class SysRoleController {

    private final ISysRoleService roleService;
    private final ISysDeptService deptService;

    /**
     * 查询角色信息列表
     */
    @SaCheckPermission("web:v1:role:list")
    @PostMapping("/list")
    public Result<RowsData<SysRoleVO>> list(@RequestBody SysRoleQueryDTO role) {
        return Result.success(roleService.selectPageRoleList(role));
    }

    /**
     * 导出角色信息列表
     */
    @Log(title = "导出角色信息列表", businessType = BusinessType.EXPORT)
    @SaCheckPermission("web:v1:role:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysRoleQueryDTO role) {
        List<SysRole> list = roleService.selectRoleList(role);
        ExcelUtil.exportExcel(list, "角色数据", SysRole.class, response);
    }

    /**
     * 根据角色编号获取详细信息
     *
     * @param roleDto 角色ID
     */
    @SaCheckPermission("web:v1:role:getInfo")
    @PostMapping(value = "/getInfo")
    public Result<SysRoleVO> getInfo(@RequestBody SelectLongDTO roleDto) {
        roleService.checkRoleDataScope(roleDto.getIdLong());
        return Result.success(roleService.selectRoleById(roleDto.getIdLong()));
    }

    /**
     * 新增角色
     */
    @SaCheckPermission("web:v1:role:add")
    @Log(title = "新增角色", businessType = BusinessType.INSERT)
    @PostMapping(value = "/add")
    public Result<Object> add(@Validated @RequestBody SysRoleAddDTO role) {
        SysRole sysRole = new SysRole();
        BeanCopyUtils.copy(role, sysRole);
        roleService.checkRoleAllowed(sysRole);
        if (!roleService.checkRoleNameUnique(sysRole)) {
            return Result.fail("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (!roleService.checkRoleKeyUnique(sysRole)) {
            return Result.fail("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        return Result.success(roleService.insertRole(role));

    }

    /**
     * 修改保存角色
     */
    @SaCheckPermission("web:v1:role:edit")
    @Log(title = "修改保存角色", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/edit")
    public Result<Object> edit(@Validated @RequestBody SysRoleAddDTO role) {
        SysRole sysRole = new SysRole();
        BeanCopyUtils.copy(role, sysRole);
        roleService.checkRoleAllowed(sysRole);
        roleService.checkRoleDataScope(role.getRoleId());
        if (!roleService.checkRoleNameUnique(sysRole)) {
            return Result.fail("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (!roleService.checkRoleKeyUnique(sysRole)) {
            return Result.fail("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        if (roleService.updateRole(role) > 0) {
            roleService.cleanOnlineUserByRole(role.getRoleId());
            return Result.success("操作成功");
        }
        return Result.fail("修改角色'" + role.getRoleName() + "'失败，请联系管理员");
    }

    /**
     * 修改保存数据权限
     */
    @SaCheckPermission("web:v1:role:edit")
    @Log(title = "修改保存数据权限", businessType = BusinessType.UPDATE)
    @PostMapping("/dataScope")
    public Result<Object> dataScope(@RequestBody SysRoleAddDTO role) {
        SysRole sysRole = new SysRole();
        BeanCopyUtils.copy(role, sysRole);
        roleService.checkRoleAllowed(sysRole);
        roleService.checkRoleDataScope(role.getRoleId());
        return Result.success(roleService.authDataScope(role));
    }

    /**
     * 状态修改
     */
    @SaCheckPermission("web:v1:role:edit")
    @Log(title = "状态修改", businessType = BusinessType.UPDATE)
    @PostMapping("/changeStatus")
    public Result<Object> changeStatus(@RequestBody SysRoleStatusDTO role) {
        SysRole sysRole = new SysRole();
        BeanCopyUtils.copy(role, sysRole);
        roleService.checkRoleAllowed(sysRole);
        roleService.checkRoleDataScope(role.getRoleId());
        return Result.success(roleService.updateRoleStatus(role));
    }

    /**
     * 删除角色
     *
     * @param roleIds 角色ID串
     */
    @SaCheckPermission("web:v1:role:remove")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    public Result<Object> remove(@RequestBody RemoveLongDTO roleIds) {
        return Result.success(roleService.deleteRoleByIds(roleIds.getRemoveIdList()));
    }

    /**
     * 获取角色选择框列表
     */
    @SaCheckPermission("web:v1:role:optionselect")
    @PostMapping("/optionselect")
    public Result<List<SysRoleVO>> optionselect() {
        return Result.success(roleService.selectRoleAll());
    }

//    /**
//     * 查询已分配用户角色列表
//     */
//    //@SaCheckPermission("web:v1:role:list")
//    @PostMapping("/authUser/allocatedList")
//    public Result<RowsData<SysUserListVO>> allocatedList(SysUserQueryDTO sysUserQuery) {
//        return Result.success(userService.selectAllocatedList(sysUserQuery));
//    }
//
//    /**
//     * 查询未分配用户角色列表
//     */
//   // @SaCheckPermission("web:v1:role:list")
//    @PostMapping("/authUser/unallocatedList")
//    public  Result<RowsData<SysUserListVO>> unallocatedList(SysUserQueryDTO sysUserQuery) {
//        return  Result.success(userService.selectUnallocatedList(sysUserQuery));
//    }

    /**
     * 取消授权用户
     */
    @SaCheckPermission("web:v1:role:edit")
    @Log(title = "取消授权用户", businessType = BusinessType.GRANT)
    @PostMapping("/authUser/cancel")
    public Result<Object> cancelAuthUser(@RequestBody SysUserRoleDTO sysUserRoleDTO) {
        return Result.success(roleService.deleteAuthUser(sysUserRoleDTO));
    }


    /**
     * 批量选择用户授权
     *
     * @param sysUserRoleDTO 角色ID
     */
    @SaCheckPermission("web:v1:role:edit")
    @Log(title = "批量选择用户授权", businessType = BusinessType.GRANT)
    @PostMapping("/authUser/selectAllByRoleId")
    public Result<Object> selectAuthUserAll(@RequestBody SysUserRoleDTO sysUserRoleDTO) {
        roleService.checkRoleDataScope(sysUserRoleDTO.getRoleId());
        return Result.success(roleService.insertAuthUsers(sysUserRoleDTO));
    }

    /**
     * 获取对应角色部门树列表
     */
    @SaCheckPermission("web:v1:role:query")
    @PostMapping(value = "/deptTreeByRoleId")
    public Result<Map<String, Object>> deptTree() {
        Map<String, Object> ajax = new HashMap<>();
        //ajax.put("checkedKeys", deptService.selectDeptListByRoleId(selectLongDTO.getIdLong()));
        ajax.put("depts", deptService.selectDeptTreeList(new SysDept()));
        return Result.success(ajax);
    }


    /**
     * 流程 角色下拉选(不分页)
     *
     * @param dto dto
     * @return List<SelectVO>
     */
    @SaCheckPermission("web:v1:role:getProcessRoleList")
    @PostMapping("/getProcessRoleList")
    public Result<List<SelectVO>> getProcessRoleList(@RequestBody UserDeptRoleSelectDTO dto) {
        return Result.success("查询成功", roleService.getProcessRoleList(dto));
    }

    /**
     * 流程 角色下拉选(分页)
     *
     * @param dto dto
     * @return RowsData<SelectVO>
     */
    @SaCheckPermission("web:v1:role:getProcessRoleList")
    @PostMapping("/getProcessRolePageList")
    public Result<RowsData<SelectVO>> getProcessRolePageList(@RequestBody UserDeptRoleSelectDTO dto) {
        return Result.success("查询成功", roleService.getProcessRolePageList(dto));
    }
}
